package com.crawler.harbour.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crawler.harbour.common.DockCode;
import com.crawler.harbour.dto.LoginParamsDto;
import com.crawler.harbour.model.Notice;
import com.crawler.harbour.model.ShipmentNew;
import com.crawler.harbour.service.INoticeService;
import com.crawler.harbour.service.IShipmentNewService;
import com.crawler.harbour.utils.AESUtil;
import com.crawler.harbour.utils.LoginUtil;
import com.crawler.harbour.utils.RuoKuai;
import com.crawler.harbour.utils.StorageDay;
import com.crawler.harbour.utils.UrlUtil;
import com.crawler.utils.BeanUtils;
import com.crawler.utils.RedisManager;
import com.crawler.utils.StringUtils;

import net.dongliu.requests.Parameter;
import net.dongliu.requests.Requests;
import net.dongliu.requests.Response;
import net.dongliu.requests.Session;

/**
 * 厦门集装箱码头集团
 *
 * @author wbsheng
 * @create 2018-03-30 9:51
 **/
@Service
@Lazy(false)
public class XHCTTask extends StorageDay{


    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(XHCTTask.class);

    @Autowired
    IShipmentNewService shipmentNewService;

    @Autowired
    private INoticeService noticeService;

    /**
     * 每天1点1分执行
     * 可进场船舶
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void incomingShip() {
    	if(!RedisManager.lock("ship:incomingShip", 0)) {
    		return;
    	}
        Session session = Requests.session();
        String jsTicket = LoginUtil.getXHCTJsTicket(session, LoginParamsDto.getLoginParams(UrlUtil.XHCTDEFAULT, UrlUtil.XHCTVALIDATE, null, null));
        Map<String, String> params = new HashMap<>();
        params.put("dataDock[view]", AESUtil.xhct("CF_CONFIGURATION", jsTicket));
        params.put("dataDock[idfield]", AESUtil.xhct("VIEWS", jsTicket));
        params.put("dataDock[textfield]", AESUtil.xhct("VIEWS", jsTicket));
        params.put("dataDock[sortorder]", "VIEWS asc");
        JSONObject jsonObject = JSONObject.parseObject("{\n" +
                "\t\"op\": \"and\",\n" +
                "\t\"rules\": [{\n" +
                "\t\t\"field\": \"CF_CONFIGURATION.VIEWS\",\n" +
                "\t\t\"value\": \"TVVREF\",\n" +
                "\t\t\"op\": \"startwith\"\n" +
                "\t}, {\n" +
                "\t\t\"field\": \"CF_CONFIGURATION.APPNAME\",\n" +
                "\t\t\"value\": \"ONLINEBUSINESSHALL\",\n" +
                "\t\t\"op\": \"equal\"\n" +
                "\t}]\n" +
                "}");
        params.put("dataDock[encrpyCondition]", AESUtil.xhct(jsonObject.toJSONString(), jsTicket));
        Response<String> selectResponse = session.post(UrlUtil.XHCTSELECT).forms(params).headers(Parameter.of("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")).send().toTextResponse();
        JSONObject jsonObject1 = JSONObject.parseObject(selectResponse.getBody());
        JSONArray dataDock = jsonObject1.getJSONArray("dataDock");
        Integer pageSize = 500;
        Map<String, String> queryParam = new HashMap<>();
        queryParam.put("pagesize", pageSize + "");
        queryParam.put("page", "1");
        queryParam.put("sortname", "PREDATE");
        queryParam.put("sortorder", "desc");
        queryParam.put("encrpyCls", AESUtil.xhct("*", jsTicket));
        for (Object o : dataDock) {
            String url=UrlUtil.XHCTHTQUERY;
            JSONObject object = JSONObject.parseObject(o.toString());
            String dock = object.get("ID").toString();
            if("TVVREF_2海润".equals(dock)) {
                url=UrlUtil.XHCTHRQUERY;
            }
            boolean mark = true;
            Integer count = 1;
            queryParam.put("page", "1");
            queryParam.put("view", AESUtil.xhct(dock, jsTicket));
            while (mark) {
                LOGGER.info("search: " + dock + "page:" + count);
                //请求数据
                Response<String> queryResponse = session.post(url).forms(queryParam).headers(Parameter.of("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")).send().toTextResponse();
                String queryResponBody = queryResponse.getBody();
                JSONObject queryJsonObject = JSONObject.parseObject(queryResponBody);
                Integer total = queryJsonObject.getInteger("Total");
                if (pageSize * count > total) {
                    mark = false;
                } else {
                    count++;
                    queryParam.put("page", count + "");
                }
                JSONArray rows = queryJsonObject.getJSONArray("Rows");
                //转化成javabean
                List<Map> xhctIncomingShips = JSONObject.parseArray(rows.toJSONString(), Map.class);
                Date date = new Date();
                List<String> IdList =new ArrayList<>();
                for (Map ship : xhctIncomingShips) {
                	ShipmentNew shipmentNew = new ShipmentNew();
                    String hashStr ="";
                    Notice notice = new Notice();
                    if("TVVREF_2海润".equals(dock)) {
                    	notice.setPortNo(DockCode._HRD);
                    	 shipmentNew.setWharfName("海润码头");
                    	 hashStr= RuoKuai.MD5(DockCode._HRD+toString(ship.get("VESSEL"))+toString(ship.get("VOYAGE")));
                    }else {
                    	notice.setPortNo(DockCode._HTD);
                    	 shipmentNew.setWharfName("海天码头");
                    	 hashStr=RuoKuai.MD5(DockCode._HTD+toString(ship.get("VESSEL"))+toString(ship.get("VOYAGE")));
                    }
                    shipmentNew.setId(hashStr);
                    ShipmentNew temp = shipmentNewService.selectById(shipmentNew.getId());
                    notice.setShipName(toString(ship.get("VESSEL")));
                    notice.setShipCnName(toString(ship.get("VESSEL1")));
                    notice.setCkShipTimer(toString(ship.get("VOYAGE")));
                    notice.setCkSailingDate(convertTime(toString(ship.get("PRELEAVEDATE"))));
                    notice.setIntoDate(convertTime(toString(ship.get("INCANDATE"))));
                    notice.setOffDate(convertTime(toString(ship.get("JFCUTDATE"))));
                    notice.setBerthDate(convertTime(toString(ship.get("PREDATE"))));
                    notice.setLeaveDate(convertTime(toString(ship.get("PRELEAVEDATE"))));
                    notice.setCutOffDate(convertTime(toString(ship.get("CUTDATE"))));
                    notice.setStatus(0);
                    notice.setCreateTime(date);
                    if(StringUtils.isNullOrEmpty(notice.getShipName())) {
                    	notice.setShipName(notice.getShipCnName());
                    }
                    shipmentNew.setLiner(toString(ship.get("SHIPOPER")));
                    shipmentNew.setSvcName(toString(ship.get("OTHERLINE")));
                    shipmentNew.setOffLadingDate(toString(ship.get("CUTDATE")));
                    shipmentNew.setShipTimer(toString(ship.get("VOYAGE")));
                    shipmentNew.setSailingDate(notice.getCkSailingDate());//这边得船期只有出口船期，航次也只有出口航次，所以保存进去得只有一条出口得数据
                    //shipmentNew.setJieguanTime(toString(ship.get("CUTDATE")));//(toString(ship.get("INCUTDATE")));截止进场
                    //shipmentNew.setCustCutDate(convertTime(toString(ship.get("JF_CLOSEDATE"))));关闸时间
                    BeanUtils.copyProperties(notice,shipmentNew , "id","status","type","shipTimer","sailingDate");
                    boolean isOk = true;
        	        if(temp!=null&&IdList.contains(temp.getId())) {
        	        	isOk = false;
        	        }
        		    if(isOk) {	
	                         if(temp !=null&&!temp.getSailingDate().equals(shipmentNew.getSailingDate())){
	                        	if(toString(temp.getSailingDate()).equals("")) {
	                        		notice.setType(0);
	                        	}else {
	                        		notice.setType(1);
	                        	}
	                            notice.setId(null);
	                            notice.setOrigValue(temp.getSailingDate());
	                            noticeService.insert(notice);
	                         } 
	                         if(temp !=null&&!temp.getOffDate().equals(shipmentNew.getOffDate())){
	                             notice.setType(2);
	                             notice.setId(null);
	                             notice.setOrigValue(temp.getOffDate());
	                             noticeService.insert(notice);
	                         }
	                        if(temp !=null&&!temp.getIntoDate().equals(shipmentNew.getIntoDate())){
	                             notice.setType(3);
	                             notice.setId(null);
	                             notice.setOrigValue(temp.getIntoDate());
	                             noticeService.insert(notice);
	                         }
	                        if(temp!=null) {
	                        	IdList.add(temp.getId());
	                        }
	                }
                    shipmentNewService.insertOrUpdateAllColumn(shipmentNew);                    
                }
                //执行添加操作
                System.out.println(xhctIncomingShips.size());
                LOGGER.info("厦门集装箱码头集团---数据添加完毕！");
            }
        }
    }
    private String convertTime(String date) {
    	if(StringUtils.isNullOrEmpty(date)) {
    		return "";
    	}
    	return date.replace("/", " ").replaceAll("\\.", "-");
    	
    }
    private String toString(Object data) {
    	if(data==null) {
    		return "";
    	}
    	return data.toString();
    	
    }
    
}
